package com.senlingspace.payment.core.refund;

import com.alibaba.fastjson2.JSON;
import com.senlingspace.common.core.domain.AjaxResult;
import com.senlingspace.common.utils.StringUtils;
import com.senlingspace.system.domain.SlkjOrder;
import com.senlingspace.system.mapper.SlkjOrderMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 退款服务实现
 *
 * @author lebronjames
 * @date 2024/07/27
 */
@Slf4j
@Service
@AllArgsConstructor
public class RefundServiceImpl implements IRefundService {

    private final SlkjOrderMapper slkjOrderMapper;
    private final RefundStrategyFactory strategyFactory;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult refundOrder(String orderId, Long operatorId) {
        if (StringUtils.isEmpty(orderId)) {
            return AjaxResult.error("订单ID不能为空！");
        }
        if (Objects.isNull(operatorId)) {
            return AjaxResult.error("操作人ID不能为空！");
        }
        try {
            Long id = Long.valueOf(orderId);
            SlkjOrder order = slkjOrderMapper.selectSlkjOrderByOrderId(id);
            if (Objects.isNull(order)) {
                return AjaxResult.error("订单不存在！");
            }
            AjaxResult result = strategyFactory.getStrategy(order.getSource())
                    .refund(order, operatorId);
            log.info("订单 [{}] 退款结果：{}", order.getOrderNumber(), JSON.toJSONString(result));
            return result;
        } catch (NumberFormatException e) {
            log.error("订单ID格式错误！", e);
            return AjaxResult.error("订单ID格式错误！");
        }
    }

}
